#include "basicai.h"
#include <QMap>

enum STATE
{
    Ready,
    Fleeing
};

struct MinionContainer
{
    GameData *GameInfo;

    STATE State;
};

QMap<int, MinionContainer> Data;

extern "C" __declspec(dllexport) void MinionInitialize(GameData *data)
{
    Data[data->PlayerID] = { data, STATE::Ready };
}

extern "C" __declspec(dllexport) void MinionTick(int playerid, QVector<MinionData> VisibleMinions, CpuCommand &command)
{
    MinionContainer &MyData = Data[playerid];

    if(MyData.GameInfo->MyMinion.Health > 0)
    {
        if(MyData.State == STATE::Fleeing)
        {
            if(MyData.GameInfo->MyMinion.Health > MyData.GameInfo->MyMinion.MaxHealth * 0.95)
                MyData.State = STATE::Ready;
        }
        else if(MyData.GameInfo->MyMinion.Health > MyData.GameInfo->MyMinion.MaxHealth * 0.5)
        {
            if(MyData.State != STATE::Fleeing)
            {
                command.Command = CMD_TYPE::CLICK;
                double distance = MyData.GameInfo->MyMinion.Sight;
                for(int i = 0; i < VisibleMinions.size(); ++i)
                {
                    double distanceX = abs(VisibleMinions[i].X - MyData.GameInfo->MyMinion.X);
                    double distanceY = abs(VisibleMinions[i].Y - MyData.GameInfo->MyMinion.Y);
                    if(VisibleMinions[i].Team != MyData.GameInfo->MyMinion.Team &&
                       (distanceX <= distance && distanceY <= distance))
                    {
                        command.X = VisibleMinions[i].X;
                        command.Y = VisibleMinions[i].Y;
                        distance = distanceX < distanceY ? distanceX : distanceY;
                    }
                }
                if(distance == MyData.GameInfo->MyMinion.Sight)
                {
                    command.X = MyData.GameInfo->EnemyBases[0].first;
                    command.Y = MyData.GameInfo->EnemyBases[0].second;
                }
            }
        }
        else
        {
            command.Command = CMD_TYPE::CLICK;
            command.X = MyData.GameInfo->OwnBase.first;
            command.Y = MyData.GameInfo->OwnBase.second;
            MyData.State = STATE::Fleeing;
        }
    }
}
